﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.Core.DBUtility;
using Microhard.Core;

namespace Microhard.JHWorkflowTrans
{
    public class JHWorkflowImpl : IWorkflow
    {
        public ExecutedResult Add(string applierUserLogginCode, string workflowCode, ITransDataInDJ jdTrans, IGetC6WorkflowConfig config, Guid pkid, string nextApprovers)
        {
            ExecutedResult result = new ExecutedResult();
            //获得基础信息
            JHFlowInfoModel info = config.GetConfig(workflowCode);
            if (info == null)
            {
                result.ErrorMsg.Add("JHWorkflowImpl.Add", "集成参数未配置");
                return result;
            }
            var biaoshi = JHWorkflowTool.GetDJBiaoshi(info.DJSN);
            var bsid = JHWorkflowTool.UpdateDJBiaoshi_Recnum(biaoshi);

            var infowflow = JHWorkflowTool.GetTemplate(info.AppID, info.DJSN);
            //发起流程
            JHSoft.WorkFlow.BLL.Approve.ApproveDeal deal = new JHSoft.WorkFlow.BLL.Approve.ApproveDeal();
            //获得流程开始节点id
            int intStartAppDID = deal.getFlowStartStepDID(info.AppID, string.Empty, infowflow.Version);
            string InstanceID = System.Guid.NewGuid().ToString().Replace("-", "");
            string usercode;
            string userName = JHWorkflowTool.GetUserNameAndUserID(applierUserLogginCode, out usercode);
            if (string.IsNullOrEmpty(userName))
            {
                userName = JHWorkflowTool.GetUserNameAndUserID(info.DefaultUserLoginCode, out usercode);
            }
            if (string.IsNullOrEmpty(userName))
            {
                result.ErrorMsg.Add("JHWorkflowImpl.Add", "流程发起人UserName无法获取");
                return result;
            }
            info.UserCode = usercode;
            int AppID;
            //创建流程实例
            if (!JHWorkflowTool.CreateFlowInstance(info.AppID, InstanceID, string.Empty, nextApprovers, infowflow.Version))
            {
                result.ErrorMsg.Add("JHWorkflowImpl.Add", "创建流程实例失败");
            }
            string strCurDate = DateTime.Now.ToString("yyyy-MM-dd");
            string strAppOTitle = userName + "的" + infowflow.WorkflowTypeName;
            //发起流程
            AppID = JHWorkflowTool.InsertFlowFirstStep(nextApprovers, info.AppID, intStartAppDID, 0, bsid, strAppOTitle, 0, strCurDate, strCurDate, 0, InstanceID);
            string strUrl = JHWorkflowTool.GetFormInstance(intStartAppDID, InstanceID);
            if (strUrl != "")
            {
                strUrl = strUrl.Replace("&httpAppID=-1", string.Empty);
                strUrl = strUrl.Replace("IsNew=0", "IsNew=1");
                strUrl = strUrl.Replace("opentype=1", "opentype=2");
            }
            //保存实例
            JHWorkflowTool.SaveFormInstance(InstanceID, string.Empty, strUrl, intStartAppDID);
            var intExecResult = JHWorkflowTool.StorageForTheMoment(info.AppID, AppID, 1, "", nextApprovers, nextApprovers, "0", "0", "", strAppOTitle, InstanceID, 0, bsid);
            if (intExecResult != 1)
            {
                result.ErrorMsg.Add("JHWorkflowImpl.Add", "暂存流程失败");
            }
            else
            {
                //保存记录
                MH_ThirdSysStartWorkflowModel tswf = new MH_ThirdSysStartWorkflowModel();
                tswf.AppID = AppID.ToString();
                tswf.ApplierUserLogginCode = applierUserLogginCode;
                tswf.Bsid = bsid;
                tswf.CreateTime = DateTime.Now;
                tswf.DjSN = info.DJSN;
                tswf.InstanceID = InstanceID;
                tswf.StartAppDID = intStartAppDID.ToString();
                tswf.strUrl = strUrl;
                tswf.SyncStatus = false;
                tswf.UserName = userName;
                tswf.Version = info.Version;
                tswf.WorkflowCode = workflowCode;
                tswf.BuzDataID = pkid;
                config.RecordSysWFInfo(tswf);

                //发送消息
                //string callContent = "<a href =\"###\" onclick=\"if(typeof(CreateNewTabWin) == 'function'){CreateNewTabWin('../" + strUrl + "');} else{parent.CreateNewTabWin('../" + strUrl + "');}\">" + strAppOTitle + "</a>";
                string strContent = "您有一个新流程：" + strAppOTitle + "，请在我的待办中及时办理！";
                JHWorkflowTool.SendCallToUser(strContent, nextApprovers);
            }
            //插入业务数据到表单
            var ext = jdTrans.SaveToDJ(bsid, pkid, applierUserLogginCode);
            if (!ext.IsSucceed)
            {
                result.ErrorMsg.Add("JHWorkflowImpl.Add", "向表单中添加业务数据失败");
                return result;
            }
            return result;
        }
        public void UpdateWorkflowStatusToBuzData(IGetC6WorkflowConfig config, List<ITransDataInDJ> jdTrans)
        {
            var unsyncData = config.GetNeedSyncWorkflowInfo();
            if (unsyncData.Count() > 0)
            {
                foreach (var m in unsyncData)
                {
                    bool finApprovedStatus = true;
                    List<ApproveInfo> ApproveInfo = new List<ApproveInfo>();
                    StringBuilder strApproveInfo = new StringBuilder();
                    var dt = JHWorkflowTool.GetApproveStatus(m.InstanceID, m.Bsid);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        for (int j = 0; j < dt.Rows.Count; j++)
                        {
                            string strApplier = dt.Rows[j]["UserName"].ToString();
                            int AppOver = int.Parse(dt.Rows[j]["App_Over"].ToString());
                            int DelFlag = int.Parse(dt.Rows[j]["Del_Flag"].ToString());
                            string apInfo = dt.Rows[j]["AppI_Content"].ToString();

                            DateTime appendTime = Convert.ToDateTime(dt.Rows[j]["App_EndTime"]);
                            bool isApproved = true;

                            if (DelFlag == 1)
                            {
                                finApprovedStatus = false;
                                isApproved = false;
                                strApproveInfo.Append(strApplier + "否决," + appendTime + "," + apInfo + "|");
                            }
                            else
                            {
                                isApproved = true;
                                strApproveInfo.Append(strApplier + "通过," + appendTime + "," + apInfo + "|");
                            }

                            ApproveInfo.Add(new JHWorkflowTrans.ApproveInfo
                            {
                                ApproverName = strApplier,
                                CreateTime = DateTime.Now,
                                IsPass = isApproved,
                                MainID = m.Bsid,
                                PKID = m.BuzDataID,
                                ApproveEndTime = appendTime,
                                Info = apInfo
                            });
                        }
                        var strApproveif = strApproveInfo.ToString().TrimEnd("|".ToString().ToCharArray());
                        //更新状态
                        config.UpdateWorkflowInfoStatus(m.FWID, strApproveif, finApprovedStatus);
                        //更新业务表状态
                        var jdt = jdTrans.SingleOrDefault(w => w.WorkflowCode == m.WorkflowCode);
                        if (jdt != null)
                        {
                            jdt.UpdateBuzDataStatus(m.BuzDataID, ApproveInfo, finApprovedStatus);
                        }
                    }
                }
            }
        }
    }
}
